<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\SysApp;
use app\model\SysMenu;
use app\model\SysPermission;

/**
 * @extends Service<AppServiec>
 */
class AppServiec extends Service
{

    public function list($page = 1, $limit = 10, $searchQuery = null)
    {
        $list = SysApp::where(function ($q) use ($searchQuery) {
            if (!empty($searchQuery['app_key'])) {
                $q = $q->where('app_key', 'like', "%" . $searchQuery['app_key'] . "%");
            }
            if (!empty($searchQuery['app_name'])) {
                $q = $q->where('app_key', 'like', "%" . $searchQuery['app_key'] . "%");
            }
        });

        $total = $list->count();
        $list = $list
            ->order('app_id desc')
            ->page($page, $limit)->select()->toArray();

        return ['total' => $total, 'list' => $list];
    }

    public function del($app_id)
    {
        $app = SysApp::where('app_id', $app_id)->find();

        if (!$app) {
            throw new BusinessException('应用不存在');
        }

        if (SysMenu::where('app_key', $app['app_key'])->find()) {
            throw new BusinessException('应用存在菜单，暂时无法删除');
        }

        if (SysPermission::where('app_key', $app['app_key'])->find()) {
            throw new BusinessException('应用存在权限，暂时无法删除');
        }

        $app->delete();
    }

    public function save($data, $app_id = null)
    {
        $saveData = [
            'app_key' => $data['app_key'],
            'app_name' => $data['app_name'],
        ];

        if (empty($app_id)) {
            $this->checkAppKeyUnique($saveData['app_key']);
            $app = SysApp::create($saveData);
            if (empty($app->app_id)) {
                throw new BusinessException('创建失败');
            }
        } else {
            $app = SysApp::where('app_id', $app_id)->find();
            if (!$app) {
                throw new BusinessException('应用不存在');
            }
            if ($app['app_key'] != $saveData['app_key']) {
                $this->checkAppKeyUnique($saveData['app_key']);
            }
            $app->save($saveData);
        }
    }

    public function info($app_id)
    {
        $app = SysApp::where('app_id', $app_id)->find();
        if (!$app) {
            throw new BusinessException('应用不存在');
        }
        return $app;
    }

    public function checkAppKeyUnique($appKey)
    {
        if (SysApp::where('app_key', $appKey)->find()) {
            throw new BusinessException('应用标识已存在');
        }
        return true;
    }

    public function select()
    {
        $list = SysApp::select()->toArray();
        return $list;
    }
}